package com.likou;

import java.util.ArrayList;
import java.util.List;

public class q39 {

    List<List<Integer>> ans = new ArrayList<>();
    List<Integer> list = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {

        DFS(candidates, target, 0);

        return ans;
    }

    private void DFS(int[] candidates, int target, int index) {
        if (target == 0) {
            ans.add(new ArrayList<>(list));
            return;
        }
        if (target < 0) {
            return;
        }
        if (index == candidates.length) {
            return;
        }

        for (int i = index; i < candidates.length; i++) {
            if (target >= candidates[i]) {
                list.add(candidates[i]);
                DFS(candidates, target - candidates[i], i);
                list.remove(list.size() - 1);
            }
        }
    }
}
